<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/14
 * Time: 18:32
 */

namespace app\api\Service;


use app\common\model\Sign;

class SignService
{
    private static $_service;

    public static function getInstance()
    {
        if( null == self::$_service ){
            self::$_service = new SignService();
        }
        return self::$_service;
    }

    public function action($user_id,Sign $sign)
    {

        if( !$sign->where('user_id',$user_id)->find() ){ //记录不存在
            $sign->insert([
                'user_id'   => $user_id,
                'daytime'   => time(),
                'continue_num'=> 1
            ]);
        }
        //今天是否签到
        $todaysign = $sign->where('daytime','>=',strtotime(date('Y-m-d')))->find();

        if( $todaysign ){
            return ['code'=>0,'msg'=>'今天已签到！'];
        }
        $yesterday = $sign->where('daytime','>=',[strtotime('-1')])->find();//昨天签到
        if( $yesterday && $yesterday['continue_num'] >= 7 ){ //已签到七天，重置签到属性
            $sign->insert([
                'user_id'   => $user_id,
                'daytime'   => time(),
                'continue_num'=> 1
            ]);
        }elseif( $yesterday && $yesterday['continue_num'] < 7 ) { //小于七天递增
            $yesterday->setInc('continue_num',1);
        }else{
            $sign->insert([
                'user_id'   => $user_id,
                'daytime'   => time(),
                'continue_num'=> 1
            ]);//新增
        }

        //todo 返钱 reward()
        return ['code'=>0,'msg'=>'签到成功！'];
    }
}